package com.hzncc.flowable_diboot.custom_field.controller;

import com.diboot.core.service.BaseService;
import com.diboot.core.util.V;
import com.diboot.core.util.S;
import com.diboot.core.util.ContextHolder;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Pagination;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.hzncc.flowable_diboot.custom_field.entity.CustomTableItemConfig;
import com.hzncc.flowable_diboot.custom_field.entity.FilterSetting;
import com.hzncc.flowable_diboot.custom_field.service.CustomTableItemConfigService;
import com.hzncc.flowable_diboot.custom_field.service.FilterSettingService;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzncc.flowable_diboot.custom_field.entity.CustomTableConfig;
import com.hzncc.flowable_diboot.custom_field.service.CustomTableConfigService;
import com.hzncc.flowable_diboot.custom_field.vo.CustomTableConfigDetailVO;
import com.hzncc.flowable_diboot.custom_field.vo.CustomTableConfigListVO;
import com.hzncc.flowable_diboot.custom_field.dto.CustomTableConfigDTO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义表格配置 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-11-14
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/custom-fields/custom-table-config")
@BindPermission(name = "自定义表格配置")
@RestController
public class CustomTableConfigController extends BaseCrudRestController<CustomTableConfig> {

    @Autowired
    private CustomTableConfigService customTableConfigService;

    @Autowired
    private CustomTableItemConfigService customTableItemConfigService;

    @Autowired
    private FilterSettingService filterSettingService;

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<CustomTableConfigListVO>> getListVOMapping(CustomTableConfigDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, CustomTableConfigListVO.class);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<CustomTableConfigDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        CustomTableConfigDetailVO detailVO = customTableConfigService.getViewObject(id, CustomTableConfigDetailVO.class);
//        Binder.bindRelations(detailVO);
        return JsonResult.OK(detailVO);
    }

    /**
     * 根据指定字段和值查询资源对象的详情VO
     *
     * @param fieldName  字段名
     * @param fieldValue 字段值
     * @return
     * @throws Exception
     */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<CustomTableConfigDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        CustomTableConfigDetailVO detailVO = customTableConfigService.getViewObject(fieldName, fieldValue, CustomTableConfigDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param customTableConfig
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<Serializable> createModelMapping(@RequestBody CustomTableConfig customTableConfig) throws Exception {
        customTableConfigService.createEntity(customTableConfig);
        List<CustomTableItemConfig> customTableItemConfigs = new ArrayList<>();
        if (S.isNotBlank(customTableConfig.getEntity())) {
            customTableItemConfigs = customTableConfigService.parsingEntity(customTableConfig.getEntity());
        } else if (S.isNotBlank(customTableConfig.getSql())) {
            customTableItemConfigs = customTableConfigService.parsingSql(customTableConfig.getSql());
            List<FilterSetting> filterSetting = customTableConfigService.getFilterSetting(customTableConfig.getSql());
            filterSetting.forEach(e -> e.setCustomTableConfigId(customTableConfig.getId()));
            filterSettingService.createOrUpdateEntities(filterSetting);
        }
        AtomicInteger sort = new AtomicInteger(1);
        customTableItemConfigs.forEach(e -> {
            e.setCustomTableConfigId(customTableConfig.getId());
            e.setSort(sort.getAndIncrement());
        });
        customTableItemConfigService.createOrUpdateEntities(customTableItemConfigs);
        return JsonResult.OK(customTableConfig.getId());
    }

    /**
     * 根据id更新资源对象
     *
     * @param customTableConfig
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody CustomTableConfig customTableConfig) throws Exception {
        customTableConfigService.updateEntity(customTableConfig);
        return JsonResult.OK();
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = customTableConfigService.deleteEntity(id);
        log.debug("删除数据 自定义表格配置:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK();
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = customTableConfigService.deleteEntities(ids);
        log.debug("批量删除数据 自定义表格配置:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK();
    }

    /**
     * 检查数据唯一性
     *
     * @param id
     * @param field
     * @param value
     * @return
     * @throws Exception
     */
    @GetMapping("/check-unique")
    public JsonResult<?> checkUnique(@RequestParam(required = false) String id, @RequestParam String field, @RequestParam String value) throws Exception {
        if (V.isEmpty(value)) {
            return JsonResult.FAIL_VALIDATION("待检查字段值不能为空");
        }
        QueryWrapper<Object> wrapper = Wrappers.query().eq(S.toSnakeCase(field), value);
        if (V.notEmpty(id)) {
            wrapper.ne(ContextHolder.getIdFieldName(getEntityClass()), id);
        }
        boolean isUnique = !customTableConfigService.exists(wrapper);
        return JsonResult.OK(isUnique);
    }

    /**
     * 解析sql
     *
     * @param sql
     * @return
     */
    @GetMapping("/parsing-sql")
    public JsonResult<List<CustomTableItemConfig>> getCustomTableItemConfig(@RequestParam String sql) {
        List<CustomTableItemConfig> list = customTableConfigService.parsingSql(sql);
        return JsonResult.OK(list);
    }


    /**
     * 解析实体类
     *
     * @param entity
     * @return
     */
    @GetMapping("/parse-entity")
    public JsonResult<List<CustomTableItemConfig>> getCustomTableItemConfigList(String entity) {
        List<CustomTableItemConfig> list = customTableConfigService.parsingEntity(entity);
        return JsonResult.OK(list);
    }

    /**
     * 获取实体类列表
     *
     * @return
     */
    @GetMapping("/entity-list")
    public JsonResult<List<LabelValue>> getEntityList() {
        List<LabelValue> entityList = customTableConfigService.findEntityList();
        return JsonResult.OK(entityList);
    }

    @GetMapping("/view-object")
    public JsonResult<List<LabelValue>> getViewObjectList(String entity) throws ClassNotFoundException {
        // 获取entity 子类
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .forPackages("com.hzncc.flowable_diboot")
                .addScanners(Scanners.SubTypes));
        List<LabelValue> entityList = new ArrayList<>();
        reflections.getSubTypesOf(Class.forName(entity))
                .forEach(e -> entityList.add(new LabelValue(e.getSimpleName(), e.getName())));
        return JsonResult.OK(entityList);
    }

    /**
     * 获取配置
     *
     * @param code
     * @return
     */
    @GetMapping("/config/{code}")
    public JsonResult<CustomTableConfigDetailVO> getConfig(@PathVariable String code) {
        return JsonResult.OK(customTableConfigService.getConfig(code));
    }

    /**
     * 保存配置
     *
     * @return
     */
    @PostMapping("/save")
    public JsonResult<String> save(@RequestBody CustomTableConfigDetailVO customTableConfigDetailVO) {
        customTableConfigService.saveConfig(customTableConfigDetailVO);
        return JsonResult.OK();
    }

    /**
     * 刷新字段
     *
     * @param id
     * @param sql
     * @param entity
     * @return
     */
    @GetMapping("/refresh-items")
    public JsonResult<List<CustomTableItemConfig>> getNewItems(String id, String sql, String entity) {
        List<CustomTableItemConfig> newItems = customTableConfigService.getNewItems(id, entity, sql);
        return JsonResult.OK(newItems);
    }

    /**
     * 获取过滤设置`
     *
     * @param sql
     * @return
     */
    @GetMapping("/filter-setting")
    public JsonResult<List<FilterSetting>> getFilterSetting(String sql) {
        List<FilterSetting> filterSettings = customTableConfigService.getFilterSetting(sql);
        return JsonResult.OK(filterSettings);
    }

    /**
     * 检查sql
     *
     * @return
     */
    @GetMapping("/check-sql")
    public JsonResult<?> checkSql(String sql) {
        //if (S.contains(sql, "where") && !S.contains(sql, "<#")) {
        //    return JsonResult.FAIL_VALIDATION("where子句需用'<##>'包裹，且where子句中不能有换行符");
        //}
        //sql = sql.replace("<#", "").replace("#>", "").replaceAll(":\\w+", "''");
        //if (SqlExecutor.validateQuery(sql)) {
        //    return JsonResult.OK(true);
        //} else {
        //    return JsonResult.FAIL_VALIDATION("sql语法错误");
        //}
        return JsonResult.OK(true);
    }

    /**
     * 检查实体
     *
     * @return
     */
    @GetMapping("/check-entity")
    public JsonResult<?> checkEntity(String entity) {
        Class clz = null;
        try {
            clz = Class.forName(entity);
        } catch (ClassNotFoundException e) {
            return JsonResult.FAIL_VALIDATION("实体不存在");
        }
        BaseService baseServiceByEntity = ContextHolder.getBaseServiceByEntity(clz);
        if (baseServiceByEntity == null) {
            return JsonResult.FAIL_VALIDATION("实体没有对应的service实现类");
        }
        return JsonResult.OK(true);
    }

    @GetMapping("/check-view-object-class")
    public JsonResult<?> checkViewObjectClass(String viewObjectClass) {
        try {
            Class.forName(viewObjectClass);
        } catch (ClassNotFoundException e) {
            return JsonResult.FAIL_VALIDATION("类不存在");
        }
        return JsonResult.OK(true);
    }

    /**
     * 复制到租户
     * @param codes
     * @param tenantId
     * @return
     */
    @PostMapping("/copy-to-tenant")
    public JsonResult<?> copyToTenant(@RequestBody List<String> codes,String tenantId){
        customTableConfigService.copyToTenant(codes,tenantId);
        return JsonResult.OK();
    }
}